<template>
  <div class="rights_container">
    <!-- 面包屑导航栏 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 角色列表卡片 -->
    <el-card class="box-card">
      <!-- 添加按钮区域 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="dialogFormVisible = true">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 角色列表表格区域 -->
      <el-table :data="rolesList" border stripe style="width: 100%">
        <!-- 展开列 -->
        <el-table-column label=">" type="expand" width="50px">
          <template slot-scope="props">
            <!-- 展开表格 -->
            <el-row
              :class="['vcenter', 'bdbottom', i1 === 0 ? 'bdtop' : '']"
              v-for="(item1, i1) in props.row.children"
              :key="item1.id">
              <!-- 一级权限渲染，占5/24宽度 -->
              <el-col :span="5">
                <el-tag closable @close="dltTagById(props.row, item1.id)">
                  {{ item1.authName }}
                </el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二和三级权限渲染，占19/24宽度 -->
              <el-col :span="19">
                <el-row
                  :class="['vcenter', i2 == 0 ? '' : 'bdtop']"
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id">
                  <!-- 二级权限渲染 -->
                  <el-col :span="6">
                    <el-tag type="success" closable @close="dltTagById(props.row, item2.id)">
                      {{ item2.authName }}
                    </el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级权限渲染 -->
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      closable
                      @close="dltTagById(props.row, item3.id)">
                      {{ item3.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column label="#" type="index"></el-table-column>
        <!-- 角色名称列 -->
        <el-table-column label="角色名称" prop="roleName" width="200"></el-table-column>
        <!-- 角色描述列 -->
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <!-- 操作列 -->
        <el-table-column label="操作" width="300">
          <template slot-scope="scope">
            <el-row>
              <!-- 编辑按钮 -->
              <el-button
                size="mini"
                type="primary"
                icon="el-icon-edit"
                @click="showEditRole(scope.row.id)">
                编辑
              </el-button>
              <!-- 删除按钮 -->
              <el-button
                size="mini"
                type="danger"
                icon="el-icon-delete"
                @click="deleteRole(scope.row.id)">
                删除
              </el-button>
              <!-- 设置按钮 -->
              <el-button
                size="mini"
                type="warning"
                icon="el-icon-star-off"
                @click="showSetRightsDialog(scope.row)">
                设置权限
              </el-button>
            </el-row>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 设置权限对话框 -->
    <el-dialog title="设置权限" :visible.sync="setRitDialogVisible">
      <!-- 树形控件 -->
      <el-tree
        :data="rightsList"
        :props="rightsProps"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="defKey"
        ref="treeRef"></el-tree>
      <span slot="footer">
        <el-button @click="setRitDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 角色列表数据
      rolesList: [],
      // tree类型权限列表数据
      rightsList: [],
      // 控制设置权限对话框的显示隐藏
      setRitDialogVisible: false,
      // 树形控件属性绑定对象
      rightsProps: {
        children: 'children',
        label: 'authName'
      },
      // 树形控件中默认选中节点id
      defKey: [],
      // 要分配的角色的id
      roleid: ''
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    // 请求角色列表数据（含权限数据）
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error(res.mate.msg)
      // console.log(res)
      this.rolesList = res.data
    },
    // 显示编辑角色
    showEditRole(id) {
      // console.log(id)
    },
    // 删除角色
    deleteRole(id) {
      // console.log(id)
    },
    // 设置角色
    setRole(id) {
      // console.log(id)
    },
    // 根据id删除标签
    dltTagById(role, ritid) {
      // console.log(role,ritid)
      // 警告弹框
      this.$confirm('是否删除改标签？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${ritid}`)
          // console.log(res)
          if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
          this.$message.success(res.meta.msg)
          // this.getRolesList()
          role.children = res.data
        })
        .catch(() => this.$message.info('已取消删除'))
    },
    // 点击显示设置权限的对话框
    async showSetRightsDialog(role) {
      // 将打开的角色的 id 存起来
      this.roleid = role.id
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) this.$message.error(res.meta.msg)
      this.rightsList = res.data
      // console.log(res);
      // 获取三级节点id
      this.getLeafKeys(role, this.defKey)
      this.setRitDialogVisible = true
    },
    // 提交设置权限
    async setRights() {
      // 获取选中节点数组合半选中数组节点id，并用展开表达式方式赋给keys数组
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const keysStr = keys.join(',')
      // console.log(keys);
      const { data: res } = await this.$http.post(`roles/${this.roleid}/rights`, { rids: keysStr })
      // console.log(res);
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
    },
    // 通过递归形式，获取角色下所有三级权限id，并保存到 defKey 数组中
    getLeafKeys(node, arr) {
      // 如果 node 节点不包含 children 属性，则是三级节点
      if (!node.children) return arr.push(node.id)
      // 递归
      node.children.forEach(item => this.getLeafKeys(item, arr))
    }
  }
}
</script>

<style lang="less" scoped>
.el-table {
  margin-top: 5px;
}

.el-tag {
  margin: 7px;
}

.bdbottom {
  border-bottom: 1px solid rgb(231, 226, 226);
  margin: 0 50px;
}

.bdtop {
  border-top: 1px solid rgb(231, 226, 226);
}

.vcenter {
  display: flex;
  align-items: center;
}
</style>
